mem
Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input
Memory is automatically released when an item expires or the cache is cleared.
By default, only the first argument is considered and it only works with primitives. If you need to cache multiple arguments or cache object
s by value, have a look at alternative caching strategies below.
Install
$ npm install mem
Usage
const mem = require('mem');
let i = 0;
const counter = () => ++i;
const memoized = mem(counter);
memoized('foo');
memoized('foo');
memoized('bar');
memoized('bar');
memoized('bar', 'foo');
Works fine with promise returning functions
const mem = require('mem');
let i = 0;
const counter = async () => ++i;
const memoized = mem(counter);
(async () => {
console.log(await memoized());
console.log(await memoized());
})();
const mem = require('mem');
const got = require('got');
const delay = require('delay');
const memGot = mem(got, {maxAge: 1000});
(async () => {
await memGot('https://sindresorhus.com');
await memGot('https://sindresorhus.com');
await delay(2000);
await memGot('https://sindresorhus.com');
})();
Caching strategy
By default, only the first argument is compared via exact equality (===
) to determine whether a call is identical.
const power = mem((a, b) => Math.power(a, b));
power(2, 2);
power(2, 3);
You will have to use the cache
and cacheKey
options appropriate to your function. In this specific case, the following could work:
const power = mem((a, b) => Math.power(a, b), {
cacheKey: arguments_ => arguments_.join(',')
});
power(2, 2);
power(2, 3);
More advanced examples follow.
Example: Options-like argument
If your function accepts an object, it won't be memoized out of the box:
const heavyMemoizedOperation = mem(heavyOperation);
heavyMemoizedOperation({full: true});
heavyMemoizedOperation({full: true});
You might want to serialize or hash them, for example using JSON.stringify
or something like serialize-javascript, which can also serialize RegExp
, Date
and so on.
const heavyMemoizedOperation = mem(heavyOperation, {cacheKey: JSON.stringify});
heavyMemoizedOperation({full: true});
heavyMemoizedOperation({full: true});
The same solution also works if it accepts multiple serializable objects:
const heavyMemoizedOperation = mem(heavyOperation, {cacheKey: JSON.stringify});
heavyMemoizedOperation('hello', {full: true});
heavyMemoizedOperation('hello', {full: true});
Example: Multiple non-serializable arguments
If your function accepts multiple arguments that aren't supported by JSON.stringify
(e.g. DOM elements and functions), you can instead extend the initial exact equality (===
) to work on multiple arguments using many-keys-map
:
const ManyKeysMap = require('many-keys-map');
const addListener = (emitter, eventName, listener) => emitter.on(eventName, listener);
const addOneListener = mem(addListener, {
cacheKey: arguments_ => arguments_,
cache: new ManyKeysMap()
});
addOneListener(header, 'click', console.log);
addOneListener(header, 'click', console.log);
addOneListener(mainContent, 'load', console.log);
Better yet, if your function’s arguments are compatible with WeakMap
, you should use deep-weak-map
instead of many-keys-map
. This will help avoid memory leaks.
API
mem(fn, options?)
fn
Type: Function
Function to be memoized.
options
Type: object
maxAge
Type: number
Default: Infinity
Milliseconds until the cache expires.
cacheKey
Type: Function
Default: arguments_ => arguments_[0]
Example: arguments_ => JSON.stringify(arguments_)
Determines the cache key for storing the result based on the function arguments. By default, only the first argument is considered.
A cacheKey
function can return any type supported by Map
(or whatever structure you use in the cache
option).
Refer to the caching strategies section for more information.
cache
Type: object
Default: new Map()
Use a different cache storage. Must implement the following methods: .has(key)
, .get(key)
, .set(key, value)
, .delete(key)
, and optionally .clear()
. You could for example use a WeakMap
instead or quick-lru
for a LRU cache.
Refer to the caching strategies section for more information.
mem.clear(fn)
Clear all cached data of a memoized function.
fn
Type: Function
Memoized function.
Tips
Cache statistics
If you want to know how many times your cache had a hit or a miss, you can make use of stats-map as a replacement for the default cache.
Example
const mem = require('mem');
const StatsMap = require('stats-map');
const got = require('got');
const cache = new StatsMap();
const memGot = mem(got, {cache});
(async () => {
await memGot('https://sindresorhus.com');
await memGot('https://sindresorhus.com');
await memGot('https://sindresorhus.com');
console.log(cache.stats);
})();
Related
- p-memoize - Memoize promise-returning & async functions